import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/views/layout/Layout.vue";
import User from "@/views/user/User.vue";
import Login from "@/views/Login.vue";
import { getToken } from "@/util/auth";

//  路由线路
const routes = [
  // 主页面
  {
    path: "/",
    name: "home",
    component: () => Layout,
    children: [
      {
        path: "user",
        name: "user",
        component: User,
      },
      {
        path: "category",
        name: "category",
        component: () => import('@/views/basic/category/Index.vue'),
      },
      {
        path: "product",
        name: "product",
        component: () => import('@/views/basic/product/Index.vue'),
      },
      {
        path: "heart",
        name: "heart",
        component: () => import('@/views/heart/Index.vue'),
      },
      {
        path: "repository",
        name: "repository",
        component: () => import('@/views/basic/repository/Index.vue'),
      },
      {
        path: "news",
        name: "news",
        component: () => import('@/views/broad/News.vue'),
      },
    ],
  },
  // 登录界面
  {
    path: "/login",
    name: "login",
    component: () => Login,
  },
  
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由首位 判断当前是否已登录
router.beforeEach((to, from, next) => {
  //说明用户访问的是登录页面 放行
  if (to.path == "/login" && !getToken()) {
    next();
    return;
  }
  //获取登录信息
  let token = getToken();
  if (token == "" || token == undefined || token == null) {
    //没有登录 跳转到登录页面
    next("/login");
    return;
  }

  if (getToken() && to.path == "/login") {
    next("/");
  }
  //登录过 直接放行
  next();
});

// 导出路由对象
export default router;
